<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;
JLoader::register('AutogeneratorHelper', AUTOGENERATOR_DIR_ROOT . '/helpers/autogenerator.php');

class AutogeneratorModelFields extends JModelList {

    public function __construct($config = array()) {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'id', 'af.id',
                'table_id', 'af.table_id',
                'xml_type_id', 'af.xml_type_id',
                'sql_field', 'af.sql_field',
                'sql_type', 'af.sql_type',
                'sql_null', 'af.sql_null',
                'sql_key', 'af.sql_key',
                'sql_default', 'af.sql_default',
                'sql_extra', 'af.sql_extra',
                'ordering', 'af.ordering',
                'allow_edit_in_list', 'af.allow_edit_in_list',
                'is_ordering_field', 'af.is_ordering_field',
                'status', 'af.status',
                'table_name', 'at.title',
                'xml_type_name', 'axt.title'
            );
        }

        parent::__construct($config);
    }

    protected function populateState($ordering = null, $direction = null) {
        $app = JFactory::getApplication();

        $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');

        $this->setState('filter.search', $search);

        $iTableId = $this->getUserStateFromRequest($this->context . '.filter.table_id', 'filter_table_id');
        $iComponentId = $this->getUserStateFromRequest($this->context . '.filter.component_id', 'filter_component_id');

        $this->setState('filter.table_id', $iTableId);
        $this->setState('filter.component_id', $iComponentId);

        parent::populateState('af.sql_field', 'asc');
    }

    protected function getStoreId($id = '') {
        // Compile the store id.
        $id .= ':' . $this->getState('filter.search');

        return parent::getStoreId($id);
    }

    public function getItems() {
        

        $aItems = parent::getItems();
        
        return $aItems;
    }

    protected function getListQuery() {
        $iComponentId = (int) $this->getState('filter.component_id');
        $iTableId = (int) $this->getState('filter.table_id');

        $db = $this->getDbo();

        // Get the table ids.
        $query = $db->getQuery(true);
        $query->select('id')->from('#__auto_table');

        if ($iComponentId > 0) {
            $query->where('component_id = ' . $iComponentId);
        }

        $db->setQuery($query);
        $aTableIds = $db->loadColumn();

        // Get the query list.
        $query = $db->getQuery(true);

        $query->select($this->getState('list.select', '
			af.id, 
			af.table_id,
			af.xml_type_id,
			
			af.sql_field, 
			af.sql_type, 
			af.sql_null, 
			af.sql_key, 
			af.sql_default, 
			af.sql_extra, 
			af.ordering, 
			af.allow_edit_in_list, 
			af.is_ordering_field, 
			af.status,
			
			at.title as table_name,
			axt.title as xml_type_name
			'))
                ->from('#__auto_field AS af')
                ->join('LEFT', '#__auto_table AS at ON at.id = af.table_id')
                ->where('at.component_id IN (' . implode(',', AutogeneratorHelper::getAvailableComponentIds()) . ')');

        if ($iComponentId > 0) {
            $query->where('at.component_id = ' . (int) $iComponentId);
        }

        if (in_array($iTableId, $aTableIds)) {
            $query->where('af.table_id = ' . (int) $iTableId);
        }

        $query->join('LEFT', '#__auto_xml_type AS axt ON axt.id = af.xml_type_id');

        // For search.
        $search = $this->getState('filter.search');
        if (!empty($search)) {
            if (stripos($search, 'id:') === 0) {
                $query->where('af.id = ' . (int) substr($search, 3));
            } else {
                $search = $db->Quote('%' . $db->escape($search, true) . '%');
                $query->where('(af.sql_field LIKE ' . $search . ')');
            }
        }

        // For ordering.
        $orderCol = $this->state->get('list.ordering', 'af.sql_field');
        $orderDirn = $this->state->get('list.direction', 'asc');
        $query->order($db->escape($orderCol . ' ' . $orderDirn));

        return $query;
    }

    public function getXMLTypeOptions() {
        $options = array();

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('axt.id AS value, axt.title AS text');
        $query->from('#__auto_xml_type AS axt');
        $query->order('axt.title ASC');

        $db->setQuery($query);

        try {
            $options = $db->loadObjectList();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        $parent = new stdClass;
        $parent->text = JText::_('JGLOBAL_ROOT_PARENT');
        $parent->value = 0;
        array_unshift($options, $parent);

        return $options;
    }

    public function getTableOptions() {
        $oDatabase = JFactory::getDbo();
        $oQuery = $oDatabase->getQuery(true);

        $oQuery->select('at.id, at.title');
        $oQuery->from('#__auto_table AS at');


        $iComponentId = $this->getState('filter.component_id');
        if ($iComponentId > 0) {
            $oQuery->where('at.component_id = ' . (int) $iComponentId);
        }

        $oQuery->order('at.ordering');

        $oDatabase->setQuery($oQuery);

        try {
            $aItems = $oDatabase->loadObjectList();
        } catch (RuntimeException $oException) {
            JError::raiseWarning(500, $oException->getMessage());
        }

        $aResult = array();

        foreach ($aItems as &$oItem) {
            $aResult[] = JHtml::_('select.option', $oItem->id, $oItem->title);
        }
        return $aResult;
    }

    public function getComponentOptions() {
        $aItems = array();

        $oDatabase = JFactory::getDbo();
        $oQuery = $oDatabase->getQuery(true);

        $oQuery->select('ac.id, ac.title');
        $oQuery->from('#__auto_component AS ac');
        $oQuery->order('ac.title ASC');

        $oDatabase->setQuery($oQuery);

        try {
            $aItems = $oDatabase->loadObjectList();
        } catch (RuntimeException $oException) {
            JError::raiseWarning(500, $oException->getMessage());
        }

        $aResult = array();

        foreach ($aItems as &$oItem) {
            $aResult[] = JHtml::_('select.option', $oItem->id, $oItem->title);
        }

        return $aResult;
    }

    public function getFields($iTableId) {
        $aItems = array();

        $oDatabase = JFactory::getDbo();
        $oQuery = $oDatabase->getQuery(true);

        $oQuery->select('af.*')
                ->from('#__auto_field AS af')
                ->where('af.table_id = ' . (int) $iTableId)
                ->order('af.ordering ASC');

        $oDatabase->setQuery($oQuery);

        try {
            $aItems = $oDatabase->loadObjectList();
        } catch (RuntimeException $oException) {
            JError::raiseWarning(500, $oException->getMessage());
        }
        
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelXMLType = JModelLegacy::getInstance('Xml_type', 'AutogeneratorModel');
        $oModelXMLElements = JModelLegacy::getInstance('Xml_elements', 'AutogeneratorModel');
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        
        foreach ($aItems as $oItem) {
            $oItem->table_title = '';
            $oItem->xml_type_title = '';
            $oItem->sql_export = '';
            $oItem->xml_export = '';
            $oTable = $oModelTable->getItem($oItem->table_id);
            $oXMLType = $oModelXMLType->getItem($oItem->xml_type_id);
            $oComponent = $oModelComponent->getItem($oTable->component_id);

            $oItem->table_title = $oTable->id > 0 ? $oTable->title : '';
            $oItem->xml_type_title = $oXMLType->id > 0 ? $oXMLType->title : '';
            $oItem->sql_export = '`' . $oItem->sql_field . '` ' . $oItem->sql_type . ($oItem->sql_null == 'NO' ? ' NOT NULL' : '') . (empty($oItem->sql_default) ? '' : ' DEFAULT "' . $oItem->sql_default . '"') . ($oItem->sql_key == 'PRI' ? ' PRIMARY KEY' : '') . (empty($oItem->sql_extra) & $oItem->sql_extra == 'auto_increment' ? '' : ' ' . strtoupper($oItem->sql_extra));

            $aXMLElements = $oModelXMLElements->getXMLElements($oItem->xml_type_id);

            $sTemp = strtoupper($oComponent->title) . '_' . strtoupper($oTable->title) . '_FIELD_' . strtoupper($oItem->sql_field);
            $aXMLText = array(
                'name="' . $oItem->sql_field . '"',
                'type="' . strtolower($oXMLType->title) . '"',
                'label="COM_' . $sTemp . '_LABEL"',
                'description="COM_' . $sTemp . '_DESC"'
            );

            AutogeneratorHelper::$aAdminLanguage['COM_' . $sTemp . '_LABEL'] = $oItem->sql_field;
            AutogeneratorHelper::$aAdminLanguage['COM_' . $sTemp . '_DESC'] = $oItem->sql_field;
            
            foreach ($aXMLElements as $aXMLElement) {
                $aXMLText[] = $aXMLElement->title . '="' . (empty($aXMLElement->custom) ? $aXMLElement->default : $aXMLElement->custom) . '"';
            }

            if ($oXMLType->title != 'List') {
                $sXMLExport = '<field ' . implode(' ', $aXMLText) . ' />';
            } else {
                $sXMLExport = '<field ' . implode(' ', $aXMLText) . ' ><option value="0">JNO</option><option value="1">JYES</option></field>';
            }

            $oItem->xml_export = htmlentities($sXMLExport);

            $oItem->xml_export_html = $sXMLExport;
        }
        
        return $aItems;
    }
    
    public function deleteAllFieldsByTableId($iTableId) {
        $oDatabase = JFactory::getDbo();

        $oQuery = $oDatabase->getQuery(true);
        $oQuery->delete($oDatabase->quoteName('#__auto_field'));
        $oQuery->where('table_id = ' . (int) $iTableId);

        $oDatabase->setQuery($oQuery);
        try {
            $bResult = $oDatabase->query();
        } catch (Exception $e) {
            if ($sError = $oDatabase->getErrorMsg()) {
                return $sError;
            }
        }
        return $bResult;
    }
    
    public function deleleAllFieldsByComponentId($iComponentId) {
        $aAllTables = AutogeneratorHelper::getAllTablesByComponentId($iComponentId);
        
        $oDatabase = JFactory::getDbo();
        
        foreach ($aAllTables as $oTable) {
            $oQuery = $oDatabase->getQuery(true);
            $oQuery->delete($oDatabase->quoteName('#__auto_field'));
            $oQuery->where('table_id = ' . (int) $oTable->id);

            $oDatabase->setQuery($oQuery);
            
            try {
                $oDatabase->query();
            } catch (Exception $e) {
                if ($sError = $oDatabase->getErrorMsg()) {
                    return $sError;
                }
            }
        }
        
        return true;
    }

}
